//全局实际产量
var DOWN_SJCL_QTY = 0;
var moInfoList = []; 
var userId =  "";  //当前登录用户id
var userName = ""; //当前登录用户姓名
var dlName = "";

layui.use(['element', 'layer'],

function() {
	var element = layui.element;
	var layer = layui.layer;
	element.on('collapse(test)',
	function(data) {
		addAllPerson();
	});
});


//顶端列表显示在线员工
function showOnlineEMP(res){
    if (!res.data) {
        return 
    }
    for (var i = 0; i < res.data.length; i++) {
        var trObj = document.createElement("tr");
        var j = i+1;
        var id = res.data[i].ID;
        var name = res.data[i].NAME;
        var mo = res.data[i].MO;
        var sec = res.data[i].SEC;
        if (mo == null) {
            mo = "";
        }
        if (sec == null) {
            sec = "";
        }
        var state = res.data[i].STATE;
        if (state == 0) {
            state = "上线";
            trObj.innerHTML ="<td style='width: 5%;'>"+j+ "</td><td style='width: 22%;'>" + id + "</td><td style='width: 17%;'>" + name + "</td><td style='width: 37%;'>" + mo + "</td><td style='width: 19%;'>"+ sec +"</td>";
        } else {
            state = '下线';
            trObj.innerHTML = "<td>" + id + "</td><td>" + name + "</td><td>" + mo + "</td><td></td>";
        }
        document.getElementById("allPerson").appendChild(trObj);
    }
    document.getElementById("h3").innerHTML = "";
    var text = document.createElement("i");
    text.innerHTML = "在线员工  <span class='layui-badge-rim'>"+res.data.length+"人</span>&nbsp;&nbsp;&nbsp;&nbsp;"+"操作人 : "+dlName;
    document.getElementById("h3").appendChild(text);
    var element = layui.element;
    element.render(); 
}

function initWxConfig(){
    var wxAppId = "";
    var timestamp = "";
    var nonce_str = "";
    var signature = "";
    var url = globalVar.URL_SHARE;
    var data = {
        urlSigna: encodeURIComponent(window.location.href)
    };
    jQuery.getJSON(url, data,
    function(res) {
        wxAppId = res.obj.appId;
        timestamp = res.obj.timesTamp;
        nonce_str = res.obj.noncestr;
        signature = res.obj.signature;
        wx.config({
            debug: false,
            // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，                                                            仅在pc端时才会打印。
            appId: wxAppId,
            // 必填，公众号的唯一标识
            timestamp: timestamp,
            // 必填，生成签名的时间戳
            nonceStr: nonce_str,
            // 必填，生成签名的随机串
            signature: signature,
            // 必填，签名，见附录1
            jsApiList: ['scanQRCode']
        });
    });
}

//初始化
$(document).ready(function() {
	document.getElementById('zhezhao').style.display="none"; 
    //正式环境
    userId = window.location.search.substr(1).split("&")[0].split("=")[1];
    userName = window.location.search.substr(1).split("&")[1].split("=")[1];
    //测试环境
    // userId = "227103";
    // userName = "郑竹成";
    dlName = decodeURI(userName);
    
    addAllPerson();
    suggestBM();
    initWxConfig();
});

//查找所有员工
function addAllPersonByBM(bmid) {
    
    var tablebody = document.getElementById('allPerson');
    tablebody.innerHTML = "";
    
    http_get_sync(
        globalVar.URL_SEARCHPERSONALLBYBM,
        {
            bmid:bmid,
        },
        function(res){
            if (res.status){
               showOnlineEMP(res);
            } else {
                layer.msg(res.message);
            }
        },
        function(err){}
    );

}

//部门选择
function changeBM(id){
    var aa = document.getElementById(id);
    var i = aa.selectedIndex;
    var bmid = aa.options[i].value;
    document.getElementById("bmList").value =bmid;
    addAllPersonByBM(bmid);
}

//右上角点击刷新
$('#h3').click(function() {
    suggestBM();
    addAllPerson();
});

//填充部门下拉列表
function suggestBM() {
    var select = $("#bmList");
    
    http_get_sync(
        globalVar.URL_SEARCHBM,
        {},
        function(res){
            if (res.status){
                $("#bmList").html("");
                 select.append("<option>全部</option>");
                for (var i = 0; i < res.data.length; i++) {
                    select.append('<option value=' + res.data[i].BU_ID + '>' +res.data[i].BU_ID+ '</option>');
                }
            } else {
                layer.msg(res.message);
            }
        },
        function(err){}
    );    
}; 

//实际产量确认按钮
function sjclok(){
    var sjcl = document.getElementById("sjcl").value;
    if(sjcl==''){
        layer.msg("请先输入实际产量!");
        return;
    }else{
        if(sjcl<=0){
            layer.msg("实际产量必须大于0!");
            return;
        }
    } 
    
    DOWN_SJCL_QTY = sjcl;
    $("#sjcl").val("");
    document.getElementById('zhezhao').style.display="none";   
    // 这里需要添加事件触发
    window.dispatchEvent(new CustomEvent('sjclInputComplete'));
};

//弹框输入实际产量
function dianwo(gdh,scxm,bb,personId){
    document.getElementById('zhezhao').style.display="";
    $("#gdh_").val(gdh);
    $("#scxm_").val(scxm);
    $("#bb_").val(bb);
    $("#personId_").val(personId);
};

//扫码按钮
function scanQRCodeClick(id){
    $(id).attr("disabled", true).css("opacity", 0.3);  
    
    wx.ready(function() {
    	wx.checkJsApi({ //判断当前客户端版本是否支持指定JS接口
    		jsApiList: ['scanQRCode'],
    		success: function(res) { // 以键值对的形式返回，可用true，不可用false。如：{"checkResult":{"scanQRCode":true},"errMsg":"checkJsApi:ok"}
    			if (res.checkResult.scanQRCode != true) {
    				layer.msg("抱歉，当前客户端版本不支持扫一扫");
    			}
    		},
    		fail: function(res) { //检测getNetworkType该功能失败时处理
    			layer.msg("checkJsApi error");
    		}
    	});
    }); //wx.ready结束
    wx.error(function(res) {
    	layer.msg("错误信息:" + JSON.stringify(res));
    });
    
    wx.scanQRCode({
    	desc: 'scanQRCode desc',
    	needResult: 1,
    	// 默认为0，扫描结果由企业微信处理，1则直接返回扫描结果，
    	scanType: ["qrCode", "barCode"],
    	// 可以指定扫二维码还是一维码，默认二者都有
    	success: function(res) {
    		console.log("调用扫描成功", res);
    		var result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果

            $("#codeValue").val(result); //显示结果
            
            http_get(
                globalVar.URL_SEARCHPERSON,
                {
                   id: result
                },
                function(res){
                    if (res.status){
                        $("#personName").val(res.data.name); //姓名
                        $("#personState").val(res.data.state); //状态
                        var select = $("#personMo");
                        $("#personMo").html("");
                        select.append("<option value =''>请选择工单</option>"); 
                        moInfoList = res.data.molist;
                        for (var i = 0; i < moInfoList.length; i++) {
                            select.append('<option value=' + moInfoList[i].mo + '>' +moInfoList[i].mo+ '</option>');
                        }       
                        if (moInfoList.length == 1){
                            select.val(moInfoList[0].mo);
                        }
                    } else {                       
                        $("#codeValue").val("");
                        $("#personName").val(""); //姓名
                        $("#personState").val(""); //状态
                        $("#personMo").val(""); //工单
                        layer.msg(res.message); 
                    }
                },
                function(err){}
            );
    	},
    	error: function(res) {
    		console.log(res);
            if (err.errMsg.indexOf('function_not_exist') > 0) {
            layer.msg("版本过低请升级");
            }
    	}
    }); //wx.scanQRcode结束
    
    $(id).attr("disabled", false).css("opacity", 1); 
}


//查找所有员工
function addAllPerson() {
    var tablebody = document.getElementById('allPerson');
    tablebody.innerHTML = "";
    
    http_get_sync(
        globalVar.URL_SEARCHPERSONALL,
        {},
        function(res){
            //查询所有员工
            if (res.status) {                
                showOnlineEMP(res);
            } else {
                layer.msg(res.message);
            }
        },
        function(err){}
    );

}
			
//判断实际产量
function pdsjcl(arr,gdh,scxm,sec){
    http_get(
        globalVar.URL_PDSJCL,
        {
            ryarr : arr+"",
            gdh: gdh,
            scxm: scxm,
            sec: sec
        },
        function(res){
            if (res.status) {
                if (res.data.isShow == "Y") {
                    var bb = res.data.bb;
                    dianwo(gdh,scxm,bb,sec);
                } else{
                    // 这里需要添加事件触发
                    window.dispatchEvent(new CustomEvent('sjclInputComplete'));
                }
            } else {
                layer.msg(res.message);
            }
        },
        function(err){
            return false;   
        }
    );
}

//确认下线按钮
function scanQRCodeDownClick(){        
    var personId = document.getElementById('codeValue').value;
    var personName = document.getElementById('personName').value;
    var personState = document.getElementById('personState').value;
    
    var gdhList = document.getElementById('personMo');
    var i = gdhList.selectedIndex;
    var gdh = gdhList.options[i].text;
                
    if (personId == '') {
        layer.msg("请先扫码工卡");
        return;
    }
    if (personName == '') {
        layer.msg("姓名为空，请等待数据刷新或重新扫码");
        return;
    }
    if (personState == '1') {
        layer.msg("当前员工已下线");
        return;
    }
    if (gdh == '请选择工单') {
        layer.msg("请先选择工单!");
        return;
    }
    $('#scanQRCodeDown').attr("disabled", true).css("opacity", 0.3);
    
    var arr = new Array();
    arr.push(personId);
    //应该优先判断是否需要输入实际产量， 如果需要， 把实际产量输入到下线中完成
    DOWN_SJCL_QTY = 0; //实际产量恢复
    
    var currentMO = moInfoList.find(moInfo => moInfo.mo === gdh);
    var scxm = currentMO.scxm;
    var sec = currentMO.sec;
    // 创建事件监听方案
    const waitForSjclInput = new Promise((resolve) => {
        // 假设 pdsjcl 完成后会触发 window 上的某个事件
        window.addEventListener('sjclInputComplete', function handler() {
            window.removeEventListener('sjclInputComplete', handler);
            resolve();
        });
         pdsjcl(arr,gdh,scxm,sec);
    });
    
    (async() => {
        // 等待用户完成产量输入
        await waitForSjclInput;
        
        // 用户输入完成后发送请求
        const response = await new Promise((resolve, reject) => {
            http_get(
                globalVar.URL_CONFIRMDOWN,
                {
                    sjcl: DOWN_SJCL_QTY, // 使用用户输入后的实际产量值
                    functionID: globalVar.FUNCTION_ID_DOWN_PAGE,  
                    opid: userId,
                    id: personId,
                    mo: gdh,
                    sec : sec,
                    scxm : scxm
                },
                resolve,
                reject
            );
        });
                           
        if (response.status) {
            var datetime = response.data.downdatetime;
            var tr = "<tr><td id='ghg'>" + personId + "</td><td>" + personName + "</td><td>" + gdh + "</td><td>" + datetime + "</td></tr>";
            $('table').append(tr);
            //addAllPerson();                
            layer.msg(personName + "下线成功");
        }else{
            layer.msg(response.message);
        }
            
        $("#codeValue").val("");
        $("#personName").val(""); //姓名		
        $("#personState").val(""); //状态
        $("#personMo").val(""); //状态
    })();
    
    // http_get(
    //     globalVar.URL_CONFIRMDOWN,
    //     {
    //         sjcl : DOWN_SJCL_QTY,
    //         functionID: globalVar.FUNCTION_ID_DOWN_PAGE,
    //         opid: userId,
    //         id: personId,
    //         mo: gdh,
    //         sec : sec,
    //         scxm : scxm
    //     },
    //     function(res){
    //         if (res.status){
    //             var datetime = res.data.downdatetime;
    //             var tr = "<tr><td id='ghg'>" + personId + "</td><td>" + personName + "</td><td>" + gdh + "</td><td>" + datetime + "</td></tr>";
    //             $('table').append(tr);
    //             //addAllPerson();                
    //             layer.msg(personName + "下线成功");
    //         } else {
    //             layer.msg(res.message);
    //         }
            
    //         $("#codeValue").val("");
    //         $("#personName").val(""); //姓名		
    //         $("#personState").val(""); //状态
    //         $("#personMo").val(""); //状态
    //     },
    //     function(err){}
    // );

    $('#scanQRCodeDown').attr("disabled", false).css("opacity", 1);   
};
            
